<template>
  <Dialog v-model="dialogVisible" title="批量导入" width="400">
    <div class="el-upload-radio">
      <span>是否仅更新已存在数据：</span>
      <el-radio-group disabled v-model="updateSupport" class="ml-4">
        <el-radio label="true" size="large">是</el-radio>
        <el-radio label="false" size="large">否</el-radio>
      </el-radio-group>
    </div>
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl + '?updateSupport=' + updateSupport"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或 <em> 点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">
          <div>
            <span>1.还没创建过导入数据文件</span>
            <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              type="primary"
              @click="importTemplate"
            >
              下载模板>>
            </el-link>
          </div>
          <div>2.已创建好导入数据文件，直接导入</div>
          <div>3.导入文件为.xls或.xlsx的excel文件，最多支持4M，一次导入不超过1000条记录。</div>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { getAccessToken, getTenantId } from '@/utils/auth'
  import * as OrgStaffArchivesApi from '@/api/config/orgPeopleArchives'
  import download from '@/utils/download'

  defineOptions({ name: 'OrgArchivesUploadForm' })

  const message = useMessage() // 消息弹窗
  const dialogVisible = ref(false) // 弹窗的是否展示
  const formLoading = ref(false) // 表单的加载中
  const uploadRef = ref()
  const importUrl = import.meta.env.VITE_BASE_URL + '/admin-api/config/org-staff-archives/import'
  const uploadHeaders = ref() // 上传 Header 头
  const fileList = ref([]) // 文件列表
  const updateSupport = ref('false') // 是否更新已经存在的数据
  /** 打开弹窗 */
  const open = () => {
    dialogVisible.value = true
    resetForm()
  }
  defineExpose({ open }) // 提供 open 方法，用于打开弹窗

  /** 提交表单 */
  const submitForm = async () => {
    if (fileList.value.length == 0) {
      message.error('请上传文件')
      return
    }
    console.log(uploadRef.value)
    // 提交请求
    uploadHeaders.value = {
      Authorization: 'Bearer ' + getAccessToken(),
      'tenant-id': getTenantId()
    }
    formLoading.value = true
    uploadRef.value!.submit()
  }

  /** 文件上传成功 */
  const emits = defineEmits(['success'])
  const submitFormSuccess = (response: any) => {
    if (response.code !== 0) {
      message.error(response.msg)
      formLoading.value = false
      return
    }
    // 拼接提示语
    const data = response.data
    let text = '上传成功数量：' + data.createStaffNames.length + ';'
    for (let username of data.createStaffNames) {
      text += '< ' + username + ' >'
    }
    text += '更新成功数量：' + data.updateStaffNames.length + ';'
    for (const username of data.updateStaffNames) {
      text += '< ' + username + ' >'
    }
    text += '更新失败数量：' + Object.keys(data.failureStaffNames).length + ';'
    for (const username in data.failureStaffNames) {
      text += '< ' + username + ': ' + data.failureStaffNames[username] + ' >'
    }
    message.alert(text)
    // 发送操作成功的事件
    dialogVisible.value = false
    emits('success')
  }

  /** 上传错误提示 */
  const submitFormError = (): void => {
    message.error('上传失败，请您重新上传！')
    formLoading.value = false
  }

  /** 重置表单 */
  const resetForm = () => {
    // 重置上传状态和文件
    formLoading.value = false
    fileList.value = []
    updateSupport.value = 'false'
    // uploadRef.value?.clearFiles()
  }

  /** 文件数超出提示 */
  const handleExceed = (): void => {
    message.error('最多只能上传一个文件！')
  }

  /** 下载模板操作 */
  const importTemplate = async () => {
    const res = await OrgStaffArchivesApi.importOrgStaffArchivesTemplate()
    download.excel(res, '员工导入模版.xls')
  }
</script>

<style lang="scss" scoped>
  .el-upload-radio {
    display: flex;
    align-items: center;
  }
</style>